﻿/**
 * SLURM FRAMEWORK
 * VERSION: Beta 1.0
 * DATE: 2012-06-13
 * AUTHOR: Ezequiel Soler
 * GNU Lesser GPL
 **/
package com.slurm
{
	public class Utils
	{
		public static function randRange(min:Number, max:Number):Number
		{
			var randomNum:Number = Math.floor(Math.random() * (max - min + 1)) + min;
			return randomNum;
		}

		public static function decimalToBinary(decimal:Number):Number
		{
			return Number(uint(decimal).toString(2));
		}

		public static function binaryToDecimal(binary:Number):Number
		{
			return Number(parseInt(String(binary), 2));
		}

		public static function trim(str:String):String
		{
			return str.split(" ").join("");
		}

		public static function trimChar(p_string:String, p_char:String = ' '):String
		{
			if (! p_string)
			{
				return '';
			}
			var regexp:RegExp = new RegExp("^" + p_char + "+|" + p_char + "+$", "g");
			return p_string.replace(regexp, '');
		}

		public static function validate(val:String, validation:String = "email", exp:String = ""):Boolean
		{
			var er:RegExp;
			switch (validation)
			{
				case "email" :
					er = /^[a-z][\w.-]+@\w[\w.-]+\.[\w.-]*[a-z][a-z]$/i;
					break;
				case "url" :
					er = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \?=.-]*)*\/?$/;
					break;
				case "phone" :
					er = /[0-9\-\(\)]/;
					break;
				case "creditcard" :
					er = /^((67\d{2})|(4\d{3})|(5[1-5]\d{2})|(6011))(-?\s?\d{4}){3}|(3[4,7])\ d{2}-?\s?\d{6}-?\s?\d{5}$/;
					break;
				case "ip" :
					er = /^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/;
					break;
				case "number" :
					er = /[0-9]/;
					break;
				case "date" :// dd/MM/yyyy
					er = /^(?:(?:0?[1-9]|1\d|2[0-8])(\/|-)(?:0?[1-9]|1[0-2]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:31(\/|-)(?:0?[13578]|1[02]))|(?:(?:29|30)(\/|-)(?:0?[1,3-9]|1[0-2])))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(29(\/|-)0?2)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/;
					break;
				default :
					er = new RegExp(exp);
					break;
			}
			return er.test(val);
		}

		public static function randomArray(array):Array
		{
			var arrayRandomize = array;
			var m = arrayRandomize.length - 1;
			for (var i=m; i>1; i--)
			{
				var alea=Math.floor(i*Math.random());
				var temp = arrayRandomize[i];
				arrayRandomize[i] = arrayRandomize[alea];
				arrayRandomize[alea] = temp;
			}
			return arrayRandomize;
		}
	}
}